package fr.nantes.univ.BackEnd;

import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import fr.nantes.univ.DAO.AddressBookDAO;
import fr.nantes.univ.EntityBeans.AddressBook;

@SuppressWarnings("serial")
public class AddressBookServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		
		String link = "http://data.nantes.fr/api/publication/ADRESSES_NM/ADRESSES_NM_STBL/content?format=xml";
		
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

		InputSource is = new InputSource(link);
		is.setEncoding("ISO-8859-1");
		
		DocumentBuilder db = null;
		try {
			db = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}
		Document dom = null;
		try {
			dom = db.parse(is);
		} catch (SAXException e) {
			e.printStackTrace();
		}
		
		Element docEle = dom.getDocumentElement();
		NodeList nl = docEle.getElementsByTagName("element");
		
		AddressBookDAO.deleteAll();
		
		if(nl != null && nl.getLength() > 0) {
			for(int i = 0; i < nl.getLength(); i++) {
				Element el = (Element) nl.item(i);
				
				String adresse = el.getElementsByTagName("name")
						.item(0).getFirstChild().getNodeValue();
				
				String numero = el.getElementsByTagName("NUMERO")
						.item(0).getFirstChild().getNodeValue();
				
				String nomCom = el.getElementsByTagName("NOMCOM")
						.item(0).getFirstChild().getNodeValue();
				
				String motDirecteur = el.getElementsByTagName("MOT_DIRECTEUR")
						.item(0).getFirstChild().getNodeValue();
				
				String codePostal = el.getElementsByTagName("CODE_POSTAL")
						.item(0).getFirstChild().getNodeValue();
				
				String rivoli = el.getElementsByTagName("RIVOLI")
						.item(0).getFirstChild().getNodeValue();
				
				String coordonnes = el.getElementsByTagName("_l")
						.item(0).getFirstChild().getNodeValue();
				
				double latitude = Double.valueOf(coordonnes.substring(2, coordonnes.indexOf(",")));
				
				double longitude = Double.valueOf(coordonnes.substring(coordonnes.indexOf(",") + 1, coordonnes.length() -1));
				
				AddressBook addressBook = new AddressBook();
				addressBook.setAdresse(adresse);
				addressBook.setNomCom(nomCom);
				addressBook.setMotDirecteur(motDirecteur);
				addressBook.setNumero(numero);
				addressBook.setRivoli(rivoli);
				addressBook.setCodePostal(codePostal);
				addressBook.setLatitude(latitude);
				addressBook.setLongitude(longitude);
				
				AddressBookDAO.insert(addressBook);
			}
		}
		
	}

}
